import { store } from "@/store";
import { defineStore } from "pinia";
import BannerApi, { type BannerListParams, type BannerType } from "@/api/system/banner";

export const useBannerStore = defineStore("banner", () => {
  const list = ref<BannerType[]>([]);

  const totalCount = ref(0);

  const totalPage = ref(0);

  const loading = reactive({
    list: false,
    create: false,
    update: false,
    delete: false,
  });

  async function fetchBannerList(params: BannerListParams) {
    loading.list = true;
    const response = await BannerApi.getBannerList(params);
    loading.list = false;
    if (response) {
      list.value = response.records;
      totalCount.value = response.total_count;
      totalPage.value = response.total_page;
    }
  }

  async function fetchCreateBanner(banner: Partial<BannerType>) {
    loading.create = true;
    await BannerApi.addBanner(banner);
    loading.create = false;
  }

  async function fetchUpdateBanner(banner: Partial<BannerType>) {
    loading.update = true;
    await BannerApi.updateBanner(banner);
    loading.update = false;
  }

  async function fetchDeleteBanner(id: number) {
    loading.delete = true;
    await BannerApi.deleteBanner(id);
    loading.delete = false;
  }

  return {
    list,
    totalCount,
    totalPage,
    loading,
    fetchBannerList,
    fetchCreateBanner,
    fetchUpdateBanner,
    fetchDeleteBanner,
  };
});

export const useBannerStoreHook = () => {
  return useBannerStore(store);
};
